package top.pmwly.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.pmwly.common.execption.BaseException;
import top.pmwly.common.constant.ReslutEnum;
import top.pmwly.common.reslut.ReslutBean;

import java.sql.SQLException;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName GlobalExceptionHandler.java
 * @Description 异常处理器
 * @createTime 2021年09月22日 11:55:00
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * SQL异常处理
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public ReslutBean sqlException(SQLException sqlEx){
        //打印错误日志
        log.error(sqlEx.getMessage(), BaseException.class);
       return ReslutBean.FAIL(ReslutEnum.FAIL_INFO);
    }

    /**
     * 自定义异常
     * @return
     */
    @ExceptionHandler(BaseException.class)
    public ReslutBean baseException(BaseException baseEx){
        //打印错误日志
        log.error(baseEx.getReslutEnum().getMsg(), BaseException.class);
        return ReslutBean.FAIL(baseEx.getReslutEnum());
    }


    /**
     * 参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    public ReslutBean bindException(BindException bindEx){
        String errMsg = bindEx.getAllErrors().get(0).getDefaultMessage();
        //打印错误日志
        log.error(errMsg, BindException.class);
        //errMsg
        return ReslutBean.FAIL(ReslutEnum.FAIL_BIND_ERROR);
    }
    /**
     * HttpRequestMethodNotSupportedException
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ReslutBean requestMethodNotSupportedException(HttpRequestMethodNotSupportedException reqEx){
        //打印错误日志
        log.error("请求的方法方有误{}",reqEx.getMessage());
        //errMsg
        return ReslutBean.FAIL(ReslutEnum.FAIL_REQUEST_METHOD);
    }

}
